<template>
  <div id="home" ref="home">
    <nav-bar class="home-nav-bar">
      <div slot="center">购物街</div>
    </nav-bar>
    <!-- 商品标题吸顶显示这个 -->
    <tab-control
      ref="tabControlFixed"
      v-show="isTabControlFixed"
      class="fixed"
      :list="titleList"
      :currentIndex="tabControlIndex"
      @tabControlClick="tabControlClick"
    ></tab-control>
    <!-- 页面滚动 -->
    <scroll
      class="wrapper"
      ref="scroll"
      :probeType="3"
      :listenScroll="true"
      :pullup="true"
      @scroll="scroll"
      @pullingUp="pullingUp"
    >
      <!-- 轮播图 -->
      <swiper
        height="129px"
        :options="{
          autoplayTime: 3000, // 轮播间隔时间，默认3s
          loop: true // 是否循环轮播
        }"
        :list="swiperList"
        @onClick="handleSwiperClick"
      ></swiper>
      <!-- 推荐 -->
      <recommend :list="recommendList"></recommend>
      <!-- 每周流行 -->
      <popular></popular>
      <!-- 商品类型选项卡 -->
      <tab-control
        ref="tabControl"
        :list="titleList"
        :currentIndex="tabControlIndex"
        @tabControlClick="tabControlClick"
      ></tab-control>
      <!-- 商品列表 -->
      <goods-list
        :list="showGoods"
        @goodsItemClick="goodsItemClick"
      ></goods-list>
    </scroll>
    <!-- 回到顶部 -->
    <back-top v-show="isShowBackTop" @click.native="backTopClick"></back-top>
  </div>
</template>

<script scoped>
import { debounce } from "common/utils";
import { getHomeMultidata, getHomeGoods } from "network/home";

import NavBar from "components/common/navbar/NavBar";
import Scroll from "components/common/scroll/Scroll";
import Swiper from "components/common/swiper/Swiper";
import TabControl from "components/content/tabControl/TabControl";
import GoodsList from "components/content/goods/GoodsList";
import BackTop from "../../components/content/backTop/BackTop";

import Recommend from "./childComps/HomeRecommend";
import Popular from "./childComps/HomePopular";

export default {
  name: "Home",
  data() {
    return {
      // 轮播图数据
      swiperList: [],
      // 推荐数据
      recommendList: [],
      // 商品类型选项卡数据
      titleList: ["流行", "新款", "精选"],
      // 商品选项卡点击后返回的选项序号
      tabControlIndex: 0,
      // 商品列表数据
      goodsList: {
        流行: {
          pageNo: 0,
          list: []
        },
        新款: {
          pageNo: 0,
          list: []
        },
        精选: {
          pageNo: 0,
          list: []
        }
      },
      // 是否显示回到顶部按钮
      isShowBackTop: false,
      // scroll组件外层商品类型选项卡组件是否显示
      isTabControlFixed: false,
      // 离开保存scroll的y值
      saveY: 0
    };
  },
  components: {
    NavBar,
    Swiper,
    Recommend,
    Popular,
    TabControl,
    GoodsList,
    Scroll,
    BackTop
  },
  computed: {
    showGoods() {
      return this.goodsList[this.titleList[this.tabControlIndex]].list;
    }
  },
  created() {
    //获取数据
    this.getHomeMultidata();
    //获取商品数据
    this.getHomeGoods("流行");
    this.getHomeGoods("新款");
    this.getHomeGoods("精选");
  },
  mounted() {
    // 监听商品图片加载完毕
    this.imgload();
  },
  activated() {
    this.$refs.scroll.refresh();
    this.$refs.scroll.scrollTo(0, this.saveY, 0);
  },
  deactivated() {
    //保存Y值
    this.saveY = this.$refs.scroll.scroll.y;
  },
  methods: {
    /**
     * 重复繁杂代码的封装
     */
    scrollRefresh() {
      this.$refs.scroll.refresh();
    },
    imgload() {
      // let refreshDebounce = debounce(this.scrollRefresh, 400);
      // this.$bus.$on("goodsImageLoad", res => {
      //   if (res.path == this.$route.path) {
      //     refreshDebounce();
      //   }
      // });
      // 监听商品图片加载完毕
      let count = 0;
      this.$bus.$on("goodsImageLoad", res => {
        if (res.path == this.$route.path) {
          if (count++ % 4 == 0) {
            try {
              this.scrollRefresh();
            } catch (err) {
              // console.log(err);
            }
          }
        }
      });
    },
    /**
     * 事件监听相关的方法
     */
    handleSwiperClick(e) {
      console.log(e);
    },
    tabControlClick(index) {
      this.tabControlIndex = index;

      // 切换后恢复上拉加载和重新计算srcoll
      this.$refs.scroll.finishPullUp();
      // this.$refs.scroll.refresh();
      setTimeout(() => {
        this.$refs.scroll.refresh();
      }, 10);
    },
    backTopClick() {
      this.$refs.scroll.scrollTo(0, 0, 400);
    },
    scroll(pos) {
      //滚动事件
      // 获取tabControl组件的offsetTop,所有组件都有一个属性$el: 用于获取组件中的元素
      let b = -pos.y >= this.$refs.tabControl.$el.offsetTop;
      // tabContent组件是否吸顶
      this.isTabControlFixed = b;
      // 是否显示回到顶部图标
      this.isShowBackTop = -pos.y >= 800;
    },
    pullingUp() {
      //上拉加载事件
      this.getHomeGoods(this.titleList[this.tabControlIndex]).then(res => {
        if (res) {
          // 恢复上拉加载事件
          this.$refs.scroll.finishPullUp();
        }
        this.$refs.scroll.refresh();
      });
    },
    goodsItemClick(goods) {
      // 商品点击事件,跳转页面
      this.$router.push({
        path: "/detail",
        query: {
          id: goods.id
        }
      });
    },
    /**
     * 网络请求相关的方法
     */
    getHomeMultidata() {
      getHomeMultidata().then(res => {
        this.swiperList = res.swiperList;
        this.recommendList = res.recommendList;
      });
    },
    getHomeGoods(type) {
      // 获取页数加一,相当于请求下一页
      const pageNo = this.goodsList[type].pageNo + 1;
      return getHomeGoods(type, pageNo).then(res => {
        if (res.data.listLength != 0) {
          // console.log(res);
          // 把一个数组追加到另一个数组里
          this.goodsList[type].list.push(...res.data.list);
          // 请求成功把页数加一
          this.goodsList[type].pageNo += 1;
        }
        return Promise.resolve(res.data.listLength != 0);
      });
    }
  }
};
</script>

<style scoped>
#home {
  position: relative;
  height: 100vh;
}
/* 导航条 */
.home-nav-bar {
  background: var(--color-tint);
  color: #fff;
  box-shadow: 1px 1px 1px rgba(0, 0, 0, 0.1);
}
.wrapper {
  height: calc(100vh - 49px - 44px);
  overflow: hidden;
}
.fixed {
  position: absolute;
  top: 43px;
  left: 0;
  right: 0;
  z-index: 9;
}
</style>
